"""
Prophet模块补丁，用于绕过Prophet导入错误问题。
当打包的应用程序无法正确加载Prophet时，此补丁会创建一个模拟的Prophet模块。
"""

import os
import sys
import importlib
from pathlib import Path

class MockProphet:
    """模拟的Prophet类，提供基本功能但不执行任何实际操作"""
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        print("警告: 使用模拟的Prophet模型，某些分析功能将不可用")
    
    def fit(self, df, *args, **kwargs):
        print("警告: 模拟Prophet.fit()，不执行实际操作")
        return self
    
    def predict(self, df=None, *args, **kwargs):
        print("警告: 模拟Prophet.predict()，返回空数据")
        import pandas as pd
        if df is not None:
            return pd.DataFrame({'ds': df['ds'], 'yhat': 0, 'yhat_lower': 0, 'yhat_upper': 0})
        return pd.DataFrame(columns=['ds', 'yhat', 'yhat_lower', 'yhat_upper'])
    
    def plot(self, *args, **kwargs):
        print("警告: 模拟Prophet.plot()，不执行实际操作")
        import matplotlib.pyplot as plt
        fig = plt.figure()
        plt.text(0.5, 0.5, "Prophet模型不可用", ha='center', va='center')
        return fig
    
    def plot_components(self, *args, **kwargs):
        print("警告: 模拟Prophet.plot_components()，不执行实际操作")
        import matplotlib.pyplot as plt
        fig = plt.figure()
        plt.text(0.5, 0.5, "Prophet模型不可用", ha='center', va='center')
        return fig

def patch_prophet():
    """尝试修补Prophet模块"""
    try:
        # 尝试正常导入prophet
        import prophet
        print("成功导入Prophet模块")
        return False  # 不需要修补
    except (ImportError, FileNotFoundError, ModuleNotFoundError) as e:
        print(f"Prophet导入错误: {e}")
        
        # 创建模拟的prophet模块
        import sys
        import types
        
        # 创建模拟的prophet模块
        mock_prophet = types.ModuleType('prophet')
        mock_prophet.__version__ = '1.0.0'
        mock_prophet.__file__ = os.path.abspath(__file__)
        
        # 添加Prophet类
        mock_prophet.Prophet = MockProphet
        
        # 添加所需的子模块
        for submodule in ['forecaster', 'serialize', 'models']:
            submock = types.ModuleType(f'prophet.{submodule}')
            setattr(mock_prophet, submodule, submock)
            sys.modules[f'prophet.{submodule}'] = submock
        
        # 替换sys.modules中的prophet
        sys.modules['prophet'] = mock_prophet
        
        print("已加载模拟的Prophet模块")
        return True  # 已修补

if __name__ == "__main__":
    patch_prophet() 